
 <!DOCTYPE HTML>
<html >
<head>
  <meta charset="UTF-8">
  
    <title>并发扣减库存方案一 | Typhoon&#39;s code space</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="typhoon">
    

    
    <meta name="description" content="在开始分析库存扣减方案之前,首先有几个概念需要明确,因为本篇分析就是在此思想的基础上得出的解决方案. 那就是CAS和幂等,下边逐个做简要解释:">
<meta name="keywords" content="并发">
<meta property="og:type" content="article">
<meta property="og:title" content="并发扣减库存方案一">
<meta property="og:url" content="http://scorpioaeolus.oschina.io/2017/07/11/并发扣减库存方案一/index.html">
<meta property="og:site_name" content="Typhoon&#39;s code space">
<meta property="og:description" content="在开始分析库存扣减方案之前,首先有几个概念需要明确,因为本篇分析就是在此思想的基础上得出的解决方案. 那就是CAS和幂等,下边逐个做简要解释:">
<meta property="og:updated_time" content="2017-07-11T14:49:55.932Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="并发扣减库存方案一">
<meta name="twitter:description" content="在开始分析库存扣减方案之前,首先有几个概念需要明确,因为本篇分析就是在此思想的基础上得出的解决方案. 那就是CAS和幂等,下边逐个做简要解释:">

    
    <link rel="alternative" href="/atom.xml" title="Typhoon&#39;s code space" type="application/atom+xml">
    
    
    <link rel="icon" href="/typhoon/img/java.png">
    
    
    <link rel="apple-touch-icon" href="/typhoon/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/typhoon/img/jacman.jpg">
    
    <link rel="stylesheet" href="/typhoon/css/style.css">
</head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/typhoon/"><img src="/typhoon/img/java.png" alt="Typhoon&#39;s code space" title="Typhoon&#39;s code space"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/typhoon/" title="Typhoon&#39;s code space">Typhoon&#39;s code space</a></h1>
				<h2 class="blog-motto"></h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/typhoon/">主页</a></li>
					
						<li><a href="/typhoon/archives">归档</a></li>
					
						<li><a href="/typhoon/about">关于</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
						<input type="hidden" name="q" value="site:scorpioaeolus.oschina.io">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/typhoon/2017/07/11/并发扣减库存方案一/" title="并发扣减库存方案一" itemprop="url">并发扣减库存方案一</a>
  </h1>
  <p class="article-author">By
       
		<a href="/typhoon/about" title="typhoon" target="_blank" itemprop="author">typhoon</a>
		
  <p class="article-time">
    <time datetime="2017-07-11T14:48:27.000Z" itemprop="datePublished"> Published 2017-07-11</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		
			<ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-CAS"><span class="toc-number">1.</span> <span class="toc-text">1.CAS</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-幂等"><span class="toc-number">2.</span> <span class="toc-text">2.幂等</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#背景"><span class="toc-number"></span> <span class="toc-text">背景</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#存在问题"><span class="toc-number"></span> <span class="toc-text">存在问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#案例分析"><span class="toc-number"></span> <span class="toc-text">案例分析</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#解决方案"><span class="toc-number"></span> <span class="toc-text">解决方案</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#以下是代码和并发测试"><span class="toc-number"></span> <span class="toc-text">以下是代码和并发测试</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#①创建库存表"><span class="toc-number">1.</span> <span class="toc-text">①创建库存表</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#②编写接口及实现"><span class="toc-number">2.</span> <span class="toc-text">②编写接口及实现</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#③单元测试"><span class="toc-number">3.</span> <span class="toc-text">③单元测试</span></a></li></ol>
		
		</div>
		
		<pre><code>在开始分析库存扣减方案之前,首先有几个概念需要明确,因为本篇分析就是在此思想的基础上得出的解决方案.
那就是CAS和幂等,下边逐个做简要解释:
</code></pre><a id="more"></a>
<h5 id="1-CAS"><a href="#1-CAS" class="headerlink" title="1.CAS"></a>1.CAS</h5><pre><code>CAS全称是Compare And Set,是java最底层的一种操作,jvm提供了unsafe类与物理机内存打交道,其原理
就是&quot;比较赋值&quot;,重要的有点事比较和赋值有严格的顺序关系,并且比较成立才会赋值.
java并发包中的原子操作类和重入锁都使用的CAS,下面拿AtomicInteger中的一段代码举例分析:
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">/**</div><div class="line">  * Atomically increments by one the current value.</div><div class="line">  *</div><div class="line">  * @return the previous value</div><div class="line">  */</div><div class="line"> public final int getAndIncrement() &#123;</div><div class="line">     for (;;) &#123;</div><div class="line">         int current = get();</div><div class="line">         int next = current + 1;</div><div class="line">         if (compareAndSet(current, next))</div><div class="line">             return current;</div><div class="line">     &#125;</div><div class="line"> &#125;</div></pre></td></tr></table></figure>
<pre><code>此方法的作用是返回当前值,并对该原子变量进行++操作;分析一下代码,①首先一个永真循环,②每次循环拿到
该原子变量的&quot;内存值&quot;暂存到current中,next就是++后要赋给原子变量的值,
③接下来调用了一个compareAndSet方法(代码如下),并根据其返回值做处理;compareAndSet的作用就是拿
current值和内存中值作比较,如果和内存中值一致,就做赋值操作返回true,如果不一致返回false,
如果为false,继续for循环重复此操作,直到成功。很明显做for循环的目的就是防止从内存取值操作到赋值
这中间有其他线程乱入,导致current失效(已经和此刻内存中的原子变量值不一致)
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"> /**</div><div class="line"> * Atomically sets the value to the given updated value</div><div class="line"> * if the current value &#123;@code ==&#125; the expected value.</div><div class="line"> *</div><div class="line"> * @param expect the expected value</div><div class="line"> * @param update the new value</div><div class="line"> * @return true if successful. False return indicates that</div><div class="line"> * the actual value was not equal to the expected value.</div><div class="line"> */</div><div class="line">public final boolean compareAndSet(int expect, int update) &#123;</div><div class="line">    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h5 id="2-幂等"><a href="#2-幂等" class="headerlink" title="2.幂等"></a>2.幂等</h5><pre><code>幂等是一个抽象的概念。举个例子说,我们java后台写的一个接口或者方法,调用一次和调用N次,如果从理论上
我们得到的结果是一样的,那么这个操作就是幂等的(查询,设置),而插入和删除是典型的非幂等操作,因为不可重现;
再举个例子,我们系统中引入消息中间件的时候,会存在消息幂等的概念,消息中间件接收到发送方的消息后
存储此消息并做唯一标识,不管其有没有收到响应或者有没有重发,中间件都不会存储两条一模一样的消息;
消息被消费方消费后,不管中间件有没有收到响应,消费方应该要做唯一标识存储消费的消息,而不会导致
重复消费同一条消息(A像中间件发消息,如果中间件没有收到消息或者收到消息后,给的响应A没有收到,
那么A将重发消息;B消费中间件存储的消息,
如果给的响应中间件没有收到,消息将会重复被B消费)


接下来开始分析库存扣减并发问题的解决方案,解决并发问题有很多方式,比如说借助redis原生的单线程阻塞操作,
zk的节点操作,以及其他封装的分布式锁操作;此处借助CAS理念和幂等使用mysql自带的表锁和行级锁实现并发操作
</code></pre><h4 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h4><pre><code>常用的扣减操作是service层操作数据库执行update Stock set stock = stock - ? where id = ?
</code></pre><h4 id="存在问题"><a href="#存在问题" class="headerlink" title="存在问题"></a>存在问题</h4><pre><code>单线程一切都运行正常,但是多线程情况下出现数据不一致问题,两个线程在同一个stock基础上进行不同的扣减,
导致后者覆盖前者
</code></pre><h4 id="案例分析"><a href="#案例分析" class="headerlink" title="案例分析"></a>案例分析</h4><pre><code>两个线程A和B同时查到库存为5,A执行操作update Stock set stock = stock - 2 where id = 1,B执行操作
update Stock set stock = stock - 3 where id = 1,
而操作的结果可能是2或者3,而不是我们期望的0;因为A B两个线程查询的时候stock=5,都是在此数字上扣减,
导致其中一个结果被覆盖,拿到错误的扣减结果,
还有一种情况是,设计往往有容错机制，例如“重试”，如果通过扣减接口来修改库存，在重试时，可能会
得到错误的数据，导致重复扣减;
重试导致错误的根本原因，是因为“扣减”操作是一个非幂等的操作，不能够重复执行，改成设置操作则不会
有这个问题
</code></pre><h4 id="解决方案"><a href="#解决方案" class="headerlink" title="解决方案"></a>解决方案</h4><pre><code>参考CAS思想,我们进行更新的时候带上期望数据库存在的旧值update Stock set stock = newValue 
where id = ? and stock = oldValue,这种情况在并发场景下,
执行update的时候如果发现oldValue和之前查出来的值不一致,那么就放弃update,返回给调用方错误码(或者抛出异常);
但是这样还是存在一个问题,例如:当前线程
是A,查到库存是5,B线程把库存扣减到3,然后C线程又把线程新增到5,那么A执行上述更新操作的时候对这
两次变更时无法感知的,其实A持有的stock=5已经和现在两次修改
后的stock=5已经完全不止一个值(不是一个版本的值),这就是典型的CAS中的ABA问题,原子变量操作是存在
ABA问题的,后边出现了AtomicStampedReference类,每一次修改后
版本号变更,此场景中我们在库存表中加一个version字段,执行更新操作的时候update Stock stock = newValue,
version = version + 1 where id = ? and stock = oldValue  and version = ?
每次修改后都会导致version变更,那么接着上边的例子,A更新的时候虽然发现stock是其期望的值,但是版本号
已经变更了两次,从而更新失败
</code></pre><h4 id="以下是代码和并发测试"><a href="#以下是代码和并发测试" class="headerlink" title="以下是代码和并发测试"></a>以下是代码和并发测试</h4><h5 id="①创建库存表"><a href="#①创建库存表" class="headerlink" title="①创建库存表"></a>①创建库存表</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">CREATE TABLE `Stock` (</div><div class="line">  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT &apos;自增主键&apos;,</div><div class="line">  `stock` int(11) NOT NULL COMMENT &apos;库存&apos;,</div><div class="line">  `version` int(11) DEFAULT NULL COMMENT &apos;版本&apos;,</div><div class="line">  `createTime` datetime NOT NULL COMMENT &apos;创建时间&apos;,</div><div class="line">  `updateTime` datetime DEFAULT NULL COMMENT &apos;最后更新时间&apos;,</div><div class="line">  PRIMARY KEY (`id`)</div><div class="line">) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=&apos;库存表&apos;;</div><div class="line"></div><div class="line">insert into Stock values(null,10,0,now(),null);-- 插入一条初始数据</div></pre></td></tr></table></figure>
<h5 id="②编写接口及实现"><a href="#②编写接口及实现" class="headerlink" title="②编写接口及实现"></a>②编写接口及实现</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div></pre></td><td class="code"><pre><div class="line">/**</div><div class="line"> * StockService接口默认实现</div><div class="line"> * </div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-07-11 12:05</div><div class="line"> * @since V1.3.0</div><div class="line"> */</div><div class="line">@Service(&quot;stockService&quot;)</div><div class="line">public class StockServiceImpl implements StockService &#123;</div><div class="line">	@Override</div><div class="line">	@Transactional</div><div class="line">	public StockResp deductStock(StockReq req) &#123;</div><div class="line">		LOGGER.info(&quot;扣减库存请求参数:&#123;&#125;&quot;,JSON.toJSONString(req));</div><div class="line">		StockResp resp = new StockResp();</div><div class="line">		resp.setThreadName(Thread.currentThread().getName());</div><div class="line">		Calendar cal = Calendar.getInstance();</div><div class="line">		if(null == req || null == req.getId() || null == req.getNeedDeduct()) &#123;</div><div class="line">			//参数非法</div><div class="line">			return resp.error(CenterEntityError.ILLEGAL_ARGUMENT_ERROR);</div><div class="line">		&#125;</div><div class="line">		Stock stock = this.stockDao.queryByPrimaryKey(req.getId());</div><div class="line">		LOGGER.info(&quot;id:&#123;&#125;对应库存记录信息:&#123;&#125;&quot;,req.getId(),JSON.toJSONString(stock));</div><div class="line">		if(null == stock) &#123;//id对应stock不存在</div><div class="line">			LOGGER.info(&quot;id:&#123;&#125;对应stock不存在&quot;,req.getId());</div><div class="line">			return resp.error(&quot;stock不存在&quot;);</div><div class="line">		&#125;</div><div class="line">		if(stock.getStock() &lt;= 0 || stock.getStock() &lt; req.getNeedDeduct()) &#123;//不足以扣减库存</div><div class="line">		LOGGER.info(&quot;id:&#123;&#125;库存为:&#123;&#125;,需要扣减的库存:&#123;&#125;,不足以抵扣&quot;,req.getId(),stock.getStock(),req.getNeedDeduct());</div><div class="line">		return resp.error(&quot;库存不足&quot;);</div><div class="line">		&#125;</div><div class="line">		Map&lt;String,Object&gt; params = new HashMap&lt;&gt;(5);</div><div class="line">		params.put(&quot;id&quot;, req.getId());</div><div class="line">		params.put(&quot;oldStock&quot;, stock.getStock());</div><div class="line">		params.put(&quot;newStock&quot;, stock.getStock() - req.getNeedDeduct());//把扣减库存转换成设置库存,</div><div class="line">		//由非幂等操作转换成幂等操作</div><div class="line">		params.put(&quot;version&quot;, stock.getVersion());</div><div class="line">		params.put(&quot;updateTime&quot;,DateUtil.formatDate(cal.getTime(), &quot;yyyy-MM-dd HH:mm:ss&quot;));</div><div class="line">		int rs = this.stockDao.adjustStock(params);</div><div class="line">		LOGGER.info(&quot;id:&#123;&#125;扣减库存dao操作结果:&#123;&#125;&quot;,req.getId(),rs);</div><div class="line">		if(rs &lt;= 0) &#123;//如果没有更新成功,按常理说需要抛RuntimeException回滚,但是只有</div><div class="line">		//一个更新操作直接返回错误码即可</div><div class="line">			//throw new ServiceRuntimeException(&quot;id:&quot;+ req.getId() + &quot;扣减库存失败&quot;);</div><div class="line">			LOGGER.info(&quot;id:&#123;&#125;扣减库存失败&quot;,req.getId());</div><div class="line">			return resp.error(&quot;扣减库存失败&quot;);</div><div class="line">		&#125;</div><div class="line">		return resp;</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line">/**</div><div class="line"> * StockDao实现</div><div class="line"> * </div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-07-11 12:46</div><div class="line"> * @since V1.3.0</div><div class="line"> */</div><div class="line">@Repository(&quot;stockDao&quot;)</div><div class="line">public class StockDao extends BaseDao implements ICommonDao&lt;Stock, Long&gt; &#123;</div><div class="line">	/**</div><div class="line">	 * 调整库存(有可能增加也有可能减少)</div><div class="line">	 * </div><div class="line">	 * @author Typhoon</div><div class="line">	 * @date 2017-07-11 16:10</div><div class="line">	 * @since V1.3.0</div><div class="line">	 * @description &lt;p&gt;由增加和扣减非幂等操作转换成幂等操作&lt;/p&gt;</div><div class="line">	 * @param params</div><div class="line">	 * @return</div><div class="line">	 */</div><div class="line">	public int adjustStock(Map&lt;String, Object&gt; params) &#123;</div><div class="line">		if (null == params || params.isEmpty()) &#123;</div><div class="line">			return -1;</div><div class="line">		&#125;</div><div class="line">		StringBuilder sql = new StringBuilder(&quot;	update	&quot;);</div><div class="line">		sql.append(TABLE_STOCK);</div><div class="line">		sql.append(&quot;	set stock = &quot;).append(CommonUtils.evalInt(params.get(&quot;newStock&quot;)));</div><div class="line">		sql.append(&quot;,version = version + 1	&quot;);</div><div class="line">		sql.append(&quot; ,updateTime =  &quot;).append(&quot;&apos;&quot;).append(params.get(&quot;updateTime&quot;)).append(&quot;&apos;&quot;);</div><div class="line">		sql.append(where).append(oneEqOne);</div><div class="line">		sql.append(and).append(&quot;	id = 	&quot;).append(CommonUtils.evalLong(params.get(&quot;id&quot;)));</div><div class="line">		sql.append(and).append(&quot;	stock = 	&quot;).append(CommonUtils.evalInt(params.get(&quot;oldStock&quot;)));</div><div class="line">		sql.append(and).append(&quot;	version = 	&quot;).append(CommonUtils.evalInt(params.get(&quot;version&quot;)));</div><div class="line">		LOGGER.info(&quot;updatesql:&#123;&#125;&quot;, sql.toString());</div><div class="line">		return this.executeSQL(centerJdbc, sql.toString());</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h5 id="③单元测试"><a href="#③单元测试" class="headerlink" title="③单元测试"></a>③单元测试</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div></pre></td><td class="code"><pre><div class="line">/**</div><div class="line">	 * 测试扣减库存操作</div><div class="line">	 * </div><div class="line">	 * @author Typhoon</div><div class="line">	 * @date 2017-07-11 14:30 Tuesday</div><div class="line">	 * @since V1.3.0</div><div class="line">	 */</div><div class="line">	@Test</div><div class="line">	public void testDeductStockConcurrent() &#123;</div><div class="line">		StockReq req = new StockReq();</div><div class="line">		req.setId(2L);</div><div class="line">		req.setNeedDeduct(3);</div><div class="line">		BlockingQueue&lt;Future&lt;StockResp&gt;&gt; queue = new ArrayBlockingQueue&lt;&gt;(20);</div><div class="line"></div><div class="line">		Future&lt;StockResp&gt; stockTask = null;</div><div class="line">		for (int i = 0; i &lt; 20; i++) &#123;</div><div class="line">			stockTask = executors.submit(new DeductStockTask(req, stockService));</div><div class="line">			try &#123;</div><div class="line">				queue.put(stockTask);</div><div class="line">			&#125; catch (InterruptedException e) &#123;</div><div class="line">				LOGGER.error(&quot;&quot;, e);</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line"></div><div class="line">		List&lt;StockResp&gt; list = new ArrayList&lt;&gt;(queue.size());</div><div class="line">		while (!queue.isEmpty()) &#123;</div><div class="line">			try &#123;</div><div class="line">				list.add(queue.take().get(5, TimeUnit.SECONDS));</div><div class="line">			&#125; catch (Exception e) &#123;</div><div class="line">				LOGGER.error(&quot;&quot;, e);</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line"></div><div class="line">		if (!list.isEmpty()) &#123;</div><div class="line">			for (int i = 0, size = list.size(); i &lt; size; i++) &#123;</div><div class="line">				LOGGER.info(&quot;响应:&#123;&#125;&quot;, JSON.toJSONString(list.get(i)));</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">		// this.stockService.deductStock(req);</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<pre><code>开了20个线程测试多次没有出现库存被扣负的情况,欢迎各位大神拿砖来拍......
</code></pre>  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/typhoon/categories/案例分析/">案例分析</a>
</div>


  <div class="article-tags">
  
  <span></span> <a href="/typhoon/tags/并发/">并发</a>
  </div>

</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://scorpioaeolus.oschina.io/2017/07/11/并发扣减库存方案一/" data-title="并发扣减库存方案一 | Typhoon&#39;s code space" data-tsina="null" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/typhoon/2017/07/12/并发扣减库存方案二/" title="并发扣减库存方案二">
  <strong>上一篇：</strong><br/>
  <span>
  并发扣减库存方案二</span>
</a>
</div>


<div class="next">
<a href="/typhoon/2017/07/08/跨域jsonp解决方案/"  title="jsonp跨域请求解决方案">
 <strong>下一篇：</strong><br/> 
 <span>jsonp跨域请求解决方案
</span>
</a>
</div>

</nav>

	


</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
 
 <ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-CAS"><span class="toc-number">1.</span> <span class="toc-text">1.CAS</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-幂等"><span class="toc-number">2.</span> <span class="toc-text">2.幂等</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#背景"><span class="toc-number"></span> <span class="toc-text">背景</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#存在问题"><span class="toc-number"></span> <span class="toc-text">存在问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#案例分析"><span class="toc-number"></span> <span class="toc-text">案例分析</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#解决方案"><span class="toc-number"></span> <span class="toc-text">解决方案</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#以下是代码和并发测试"><span class="toc-number"></span> <span class="toc-text">以下是代码和并发测试</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#①创建库存表"><span class="toc-number">1.</span> <span class="toc-text">①创建库存表</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#②编写接口及实现"><span class="toc-number">2.</span> <span class="toc-text">②编写接口及实现</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#③单元测试"><span class="toc-number">3.</span> <span class="toc-text">③单元测试</span></a></li></ol>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  


  
<div class="categorieslist">
	<p class="asidetitle">Categories</p>
		<ul>
		
		  
			<li><a href="/typhoon/categories/dubbo/" title="dubbo">dubbo<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java性能优化/" title="java性能优化">java性能优化<sup>17</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java源码分析/" title="java源码分析">java源码分析<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/motan/" title="motan">motan<sup>2</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/spring/" title="spring">spring<sup>11</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springboot/" title="springboot">springboot<sup>28</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springmvc/" title="springmvc">springmvc<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/容器/" title="容器">容器<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/工具/" title="工具">工具<sup>7</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/性能优化/" title="性能优化">性能优化<sup>5</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/架构/" title="架构">架构<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/案例分析/" title="案例分析">案例分析<sup>13</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/缓存/" title="缓存">缓存<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/面试题/" title="面试题">面试题<sup>1</sup></a></li>
		  
		
		</ul>
</div>


  
<div class="tagslist">
	<p class="asidetitle">Tags</p>
		<ul class="clearfix">
		
			
				<li><a href="/typhoon/tags/springboot/" title="springboot">springboot<sup>28</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/java性能优化/" title="java性能优化">java性能优化<sup>9</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/限流/" title="限流">限流<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring5/" title="Spring5">Spring5<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/案例分析/" title="案例分析">案例分析<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/性能优化/" title="性能优化">性能优化<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring/" title="Spring">Spring<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo/" title="dubbo">dubbo<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/分页/" title="分页">分页<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/并发/" title="并发">并发<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/异常拦截/" title="异常拦截">异常拦截<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo分布式事务/" title="dubbo分布式事务">dubbo分布式事务<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/自带图片/" title="自带图片">自带图片<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/svn导出mvn项目/" title="svn导出mvn项目">svn导出mvn项目<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo过滤器/" title="dubbo过滤器">dubbo过滤器<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/排序性能对比/" title="排序性能对比">排序性能对比<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/ListenableFuture/" title="ListenableFuture">ListenableFuture<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/PropertyChangeListener/" title="PropertyChangeListener">PropertyChangeListener<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/jdbcTemplate高可用/" title="jdbcTemplate高可用">jdbcTemplate高可用<sup>1</sup></a></li>
			
		
		</ul>
</div>


  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
        
          <li>
            
            	<a href="https://coderq.com" target="_blank" title="一个面向程序员交流分享的新一代社区">码农圈</a>
            
          </li>
        
          <li>
            
            	<a href="http://wuchong.me" target="_blank" title="Jark&#39;s Blog">Jark&#39;s Blog</a>
            
          </li>
        
    </ul>
</div>

  


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>

  <div class="weiboshow">
  <p class="asidetitle">Weibo</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=null&verifier=b3593ceb&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hello ,I&#39;m a java coder. <br/>
			This is my blog,believe it or not.</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		
		
		
		
		
		
		
		
		
		<a href="mailto:ScorpioAeolus@163.com" target="_blank" class="icon-email" title="Email Me"></a>
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2019 
		
		<a href="/typhoon/about" target="_blank" title="typhoon">typhoon</a>
		
		
		</p>
</div>
</footer>
    <script src="/typhoon/js/jquery-2.0.3.min.js"></script>
<script src="/typhoon/js/jquery.imagesloaded.min.js"></script>
<script src="/typhoon/js/gallery.js"></script>
<script src="/typhoon/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>









<link rel="stylesheet" href="/typhoon/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/typhoon/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="Back to Top"><img src="/typhoon/img/scrollup.png"/></a>
	</div>
	<script src="/typhoon/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
